package elitech.vietnam.autoupdate;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.util.Log;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.extend.AsyncTask;

public class CheckVersionTask extends AsyncTask<String, Integer, Integer> {
	private String AppName;
	private String BuildVersionPath = "";
	private Context context;
	private int VersionCode = 0;
	private String VersionName = "";

	class PInfo {
		private String appname = "";
		private String versionName = "";
		private int versionCode = 0;
	}

	public CheckVersionTask(Context context) {
		this.context = context;
	}

	@Override
	protected Integer doInBackground(String... params) {
		if (params.length == 0)
			return 0;
		if (params[0].equals("") == true)
			return 0;
		AppName ="Weather And Fashion";// context.getResources().getString(R.string.app_name);
		BuildVersionPath = "http://eli6.cafe24.com/AutoUpdateAndroid/Shopping/auto_update.txt".toString();
		//BuildVersionPath = "http://192.168.1.113/AutoUpdate_Fashion/auto_update.txt"
		//		.toString();
		// option.setMyVersion(MyVersionName);
		// app.setOption(option);
		try {
			GetVersionFromServer(BuildVersionPath);
			boolean rs = checkInstalledApp(AppName.toString());
			if (rs) {
				String str = context.getResources().getString(R.string.your_version)
						+ " "
						+ getInstallPackageVersionInfo(AppName.toString())
								.toString()
						+ context.getResources().getString(R.string.you_want_install)
						+ " " + VersionName.toString() + "?";
				Intent intent = new Intent(Constants.BROADCAST);
				Bundle extras = new Bundle();  
		        extras.putString(Constants.MESSAGE_INFO, str); 
		        extras.putInt(Constants.VERSION_CODE,VersionCode);
		        intent.putExtras(extras);
		        context.sendBroadcast(intent);
			} else {
				//Nothing
			}
		} catch (Exception er) {
			Log.e("Auto update", er.getMessage());
		}

		return 1;
	}

	public String GetVersionFromServer(String BuildVersionPath)
			throws Exception {
		URL u;
		// try {
		u = new URL(BuildVersionPath.toString());

		HttpURLConnection c = (HttpURLConnection) u.openConnection();
		c.setRequestMethod("GET");
		c.setDoOutput(true);
		c.connect();
		InputStream in = c.getInputStream();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		byte[] buffer = new byte[1024];
		int len1 = 0;
		while ((len1 = in.read(buffer)) != -1) {
			baos.write(buffer, 0, len1); // Write Into ByteArrayOutputStream
											// Buffer.
		}
		String temp = "";
		String s = baos.toString();
		int iPost = s.indexOf("=");
		if (iPost == -1)
			return VersionName;
		temp = s.substring(iPost + 2, s.indexOf(";"));
		iPost = s.lastIndexOf("=");
		temp += s.substring(iPost + 1, s.lastIndexOf(";"));
		temp.trim();
		String[] fields = temp.split(" ");
		VersionCode = Integer.parseInt(fields[0].toString());//
		VersionName = fields[1].toString();
		baos.close();
		c.disconnect();
		return VersionName;
	}

	/**
	 * Check app install on device
	 * 
	 * @param appName
	 *            App name
	 */
	private boolean checkInstalledApp(String appName) throws Exception {
		return getPackages(appName);
	}

	/**
	 * Get packet info app install on device
	 * 
	 * @param appName
	 *            App name
	 */
	private boolean getPackages(String appName) throws Exception {

		ArrayList<PInfo> apps = getInstalledApps(false); /*
														 * false = no system
														 * packages
														 */
		int max = apps.size();

		for (int i = 0; i < max; i++) {
			if (apps.get(i).appname.toString().equals(appName.toString())) {
				if (VersionCode <= apps.get(i).versionCode) {
					return false;
				} else if (VersionCode > apps.get(i).versionCode) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Get version code of app
	 * 
	 * @param getSysPackages
	 *            true ystem packages - false no system packages
	 */
	private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
		ArrayList<PInfo> res = new ArrayList<PInfo>();
		List<PackageInfo> packs = context.getPackageManager()
				.getInstalledPackages(0);

		for (int i = 0; i < packs.size(); i++) {
			PackageInfo p = packs.get(i);
			if ((!getSysPackages) && (p.versionName == null)) {
				continue;
			}
			if (p.applicationInfo.loadLabel(context.getPackageManager())
					.toString().equals(AppName)) {
				PInfo newInfo = new PInfo();
				newInfo.appname = p.applicationInfo.loadLabel(
						context.getPackageManager()).toString();
				newInfo.versionName = p.versionName;
				newInfo.versionCode = p.versionCode;
				res.add(newInfo);
				return res;
			}
		}
		return res;
	}

	public String getInstallPackageVersionInfo(String appName) {
		String InstallVersion = "";
		ArrayList<PInfo> apps = getInstalledApps(false); /*
														 * false = no system
														 * packages
														 */
		final int max = apps.size();
		for (int i = 0; i < max; i++) {
			// apps.get(i).prettyPrint();

			if (apps.get(i).appname.toString().equals(appName.toString())) {
				// InstallVersion = "Install Version Code: "+
				// apps.get(i).versionCode+
				// " Version Name: "+ apps.get(i).versionName.toString();
				InstallVersion = apps.get(i).versionName.toString();
				break;
			}
		}
		return InstallVersion.toString();
	}
}
